<template>
  <div class="main">
    <div class="air-column">
      <h2>乘机人</h2>
      <el-form class="member-info" :model="{ users }" ref="userForm">
        <div
          class="member-info-item"
          v-for="(user, index) in users"
          :key="user.xid"
        >
          <el-form-item
            label="乘机人类型"
            :prop="'users.' + index + '.username'"
            :rules="rules.username"
          >
            <el-input
              placeholder="姓名"
              class="input-with-select"
              v-model="user.username"
            >
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="成人" value="1"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <el-form-item
            label="证件类型"
            class="papersType"
            :prop="'users.' + index + '.id'"
            :rules="rules.id"
          >
            <el-input
              placeholder="证件号码"
              class="input-with-select"
              v-model="user.id"
            >
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="身份证" value="1" :checked="true"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers"
        >添加乘机人</el-button
      >
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <div>
        <div
          class="insurance-item"
          v-for="insurance in flightsData.insurances"
          :key="insurance.id"
        >
          <el-checkbox-group v-model="insurances">
            <el-checkbox :label="insurance.id" border>
              {{
                `${insurance.type}: ￥${insurance.price}/份x${users.length} 最高赔付${insurance.compensation}`
              }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
    </div>

    <div class="air-column">
      <h2>发票</h2>
      <el-checkbox v-model="invoice">发票</el-checkbox>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          label-width="60px"
          :model="{ contactName, contactPhone, captcha }"
          :rules="rules"
          ref="contactForm"
        >
          <el-form-item label="姓名" prop="contactName">
            <el-input v-model="contactName"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone">
            <el-input placeholder="请输入内容" v-model="contactPhone">
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="captcha"></el-input>
          </el-form-item>
        </el-form>
        <el-button
          v-if="$store.state.user.userInfo.token"
          type="warning"
          class="submit"
          @click="handleSubmit"
          >提交订单</el-button
        >
        <!-- 登录注册模块 -->
        <div v-else>
          <el-container class="container">
            <el-row type="flex" justify="center" align="middle" class="main">
              <div class="form-wrapper">
                <el-row type="flex" justify="center" class="tabs">
                  <span> 登录 </span>
                </el-row>
                <LoginForm />
              </div>
            </el-row>
          </el-container>
        </div>
        <!-- 处理惰性求值 渲染计算属性返回的值 -->
        <div>{{ flightsAmount }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import LoginForm from "@/components/user/LoginForm";

export default {
  components: { LoginForm },
  data() {
    return {
      users: [
        {
          username: "陈先生",
          id: "441414141414141414",
          xid: new Date().getTime(),
        },
      ],
      insurances: [],
      contactName: "陈学生",
      contactPhone: "13111111111",
      // 发票
      invoice: false,
      // 验证码
      captcha: "000000",
      rules: {
        username: [
          {
            required: true,
            message: "输入乘机人姓名不能为空",
            trigger: "blur",
          },
        ],
        id: [
          {
            required: true,
            message: "输入乘机人身份证号不能为空",
            trigger: "blur",
          },
          {
            // 身份证是18位的数字
            pattern: /^\d{18}$/,
            message: "请输入的身份证号是18位的数字",
            trigger: "blur",
          },
        ],
        contactName: [
          {
            required: true,
            message: "输入联系人姓名不能为空",
            trigger: "blur",
          },
        ],
        contactPhone: [
          {
            required: true,
            message: "输入联系人电话号码不能为空",
            trigger: "blur",
          },
          {
            //输入正确的电话号码格式
            pattern: /^1[3456789]\d{9}$/,
            message: "请输入正确的电话号码格式",
            trigger: "blur",
          },
        ],
        captcha: [
          {
            required: true,
            message: "输入验证码不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  props: {
    flightsData: Object,
  },
  mounted() {
    // 加载页面就求一次当前机票价格
    this.flightsAmount;
  },
  // 使用计算属性处理价格
  computed: {
    // 计算机票预定的总价格
    flightsAmount() {
      // 判断请求是否完成 即获取到父元素发送过来的数据flightsData
      // if (this.flightsData.insurances) {
      // console.log(this.flightsData, "flightsData");
      // 机票价格=机票单价*乘机人数量

      const flightsPrice =
        this.flightsData.seat_infos.org_settle_price * this.users.length;
      console.log(this.flightsData.base_price, this.users.length, 111);
      //保险价格=意外险单价*乘机人数量+延误险单价*乘机人数量
      let insurancesPrice = 0;
      // 遍历购买保险的数组数据
      this.insurances.forEach((index) => {
        // index表示购买保险的类型
        // 遍历原本保险类型的数组数据
        this.flightsData.insurances.forEach((insurance) => {
          // 根据购买保险的类型与原本全部保险类型匹配情况进行计算价格
          if (index == insurance.id) {
            insurancesPrice += insurance.price * this.users.length;
          }
        });
      });
      // console.log(flightsPrice, insurancesPrice, 123);
      // 购买总价=机票价格+保险价格
      const flightAmount = flightsPrice + insurancesPrice;
      // console.log(flightAmount, "flightAmount");
      //将计算的总价 发送到父页面
      this.$emit("sentFlightAmount", flightAmount);
      // } else {
      //   console.log("没有获取到this.flightsData");
      // }
      // 为了处理计算属性的惰性求值 即需要渲染才能触发但又要不让他显示内容 就返回一个空字符串
      return "";
    },
  },
  // watch: {
  //   // 监听乘机人数量变化重新计算价格 页面加载是需要计算一次价格 可以使用一下方法处理监听函数
  //   users() {
  //     // handler() {
  //     // console.log(this.flightsData, "获取需要的数据");
  //     // 重新计算价格
  //     this.flightsAmount();
  //     // },
  //     // 页面加载时就触发一次该监听函数 即计算一次价格
  //     // immediate: true,
  //   },
  //   insurances() {
  //     // handler() {
  //     // 重新计算价格
  //     this.flightsAmount();
  //     // },
  //     // 页面加载时就触发一次该监听函数 即计算一次价格
  //     // immediate: true,
  //   },
  // },
  methods: {
    // 删除乘机人
    handleDeleteUser(index) {
      this.users.splice(index, 1);
    },
    // 添加乘机人
    handleAddUsers() {
      this.users.push({
        username: "",
        id: "",
        xid: new Date().getTime(),
      });
    },
    // 发送验证码
    handleSendCaptcha() {
      this.$axios({
        method: "post",
        url: "/captchas",
        data: {
          tel: this.contactPhone,
        },
      }).then((res) => {
        // console.log(res);
        this.$message.success("验证成功：" + res.data.code);
      });
    },
    // 发送请求提交表单
    seatSubmit() {
      const data = {
        users: this.users,
        insurances: this.insurances,
        contactName: this.contactName,
        contactPhone: this.contactPhone,
        invoice: this.invoice,
        seat_xid: this.$route.query.seat_xid,
        air: this.$route.query.id,
        captcha: this.captcha,
      };
      // 如果校验成功就发送请求提交机票信息
      // 提交表单发送请求 提交机票信息
      this.$axios({
        method: "post",
        url: "/airorders",
        data,
        headers: {
          Authorization: "Bearer " + this.$store.state.user.userInfo.token,
        },
      }).then((res) => {
        console.log(res.data);
        // 带上支付信息得到id跳转到支付页面
        if (res.data.message == "订单提交成功") {
          this.$router.push("/air/pay?id=" + res.data.data.id);
        }
      });
    },
    // 点击触发提交表单
    async handleSubmit() {
      // 使用promise.all处理不同表单的校验
      const [userValid, contactVaild] = await Promise.all([
        this.$refs.userForm.validate(),
        this.$refs.contactForm.validate(),
      ]);

      if (userValid && contactVaild) {
        // 发送请求
        this.seatSubmit();
      }
    },
  },
};
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
.member-info /deep/ .el-form-item {
  margin-bottom: 0;
}

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
  .papersType {
    padding-top: 4px;
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 16px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  /deep/ .el-input {
    width: 50%;
  }
  /deep/ .el-form-item__label:before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }
  /deep/.el-form-item__label {
    padding-right: 8px;
  }
  .container {
    border: 1px solid #000;
    background: url(http://157.122.54.189:9095/assets/images/th03.jfif) center 0;
    height: 400px;
    // min-width: 1000px;
    /deep/ .el-input {
      width: 100%;
    }
    .main {
      // width: 1000px;
      height: 100%;
      margin: 0 auto;
      position: relative;

      .form-wrapper {
        width: 400px;
        margin: 0 auto;
        background: #fff;
        box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
        overflow: hidden;

        .tabs {
          background-color: #eee;
          span {
            display: block;
            width: 50%;
            height: 50px;
            box-sizing: border-box;
            border-top: 2px #eee solid;
            // background: #eee;
            line-height: 48px;
            text-align: center;
            cursor: pointer;
            color: #666;
            font-weight: bold;
            /*   &.active {
              color: orange;
              border-top-color: orange;
              background: #fff;
              font-weight: bold;
            } */
          }
        }
      }
    }
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}
</style>